package com.company.socket.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;



public class TransferServer {

	private int defaultBindPort = Constants.DEFAULT_BIND_PORT;	//默认监听端口号为10000
	private int tryBindTimes = 0;	//初始的绑定端口的次数设定为0

	private ServerSocket serverSocket;	//服务套接字等待对方的连接和文件发送

	private ExecutorService executorService;	//线程池
	private final int POOL_SIZE = 4;			//单个CPU的线程池大小

	private static ArrayList<String> fileList = new ArrayList<String>();

    private String sendFilePath = Constants.SEND_FILE_PATH;

		/**
		 * * 不带参数的构造器，选用默认的端口号
		 * * @throws Exception
		 * */
	public TransferServer() throws Exception{
		try {
			this.bingToServerPort(defaultBindPort);
			executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
			System.out.println("开辟线程数 ：" + Runtime.getRuntime().availableProcessors() * POOL_SIZE);

			getFilePath(sendFilePath);

			} catch (Exception e) {
				throw new Exception("绑定端口不成功!");
				}
		}

		/**
	     * 带参数的构造器，选用用户指定的端口号
	     * @param port
	     * @throws Exception
	     */
	public TransferServer(int port) throws Exception{
		try {
	            this.bingToServerPort(port);
	            executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
	        } catch (Exception e) {
	            throw new Exception("绑定端口不成功!");
	        }
	    }

	    private void bingToServerPort(int port) throws Exception{
	        try {
	            serverSocket = new ServerSocket(port);
	            System.out.println(port);
	            System.out.println("服务启动!");
	        } catch (Exception e) {
	            this.tryBindTimes = this.tryBindTimes + 1;
	            port = port + this.tryBindTimes;
	            if(this.tryBindTimes >= 20){
	                throw new Exception("您已经尝试很多次了，但是仍无法绑定到指定的端口!请重新选择绑定的默认端口号");
	            }
	            //递归绑定端口
	            this.bingToServerPort(port);
	        }
	    }

	    public void service(){
	        Socket socket = null;
	        while (true) {
	            try {
	                socket = serverSocket.accept();
	                executorService.execute(new Handler(socket));
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
	    }

	    private void getFilePath(String dirPath){
	        File dir = new File(dirPath);
	        File[] files = dir.listFiles();
	        if(files == null){
	            return;
	        }
	        for(int i = 0; i < files.length; i++){
	            if(files[i].isDirectory()){
	                getFilePath(files[i].getAbsolutePath());
	            }
	            else {
	                fileList.add(files[i].getAbsolutePath());
	            }
	        }
	    }

	    private Vector<Integer> getRandom(int size){
	        Vector<Integer> v = new Vector<Integer>();
	        Random r = new Random();
	        boolean b = true;
	        while(b){
	            int i = r.nextInt(size);
	            if(!v.contains(i))
	                v.add(i);
	            if(v.size() == size)
	                b = false;
	        }
	        return v;
	    }

	    class Handler implements Runnable{
	        private Socket socket;
//			private DataInputStream dis;
			public Handler(Socket socket){
	            this.socket = socket;
	        }

	        public void run() {

	            File file;
	            System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());

	            int bufferSize = 8192;
                byte[] buf = new byte[bufferSize];
                try {
					BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
					byte[] buff = new byte[128];
					int size = 0;
					String fileName=null;
					while (( size = in.read(buff,0,buff.length)) != -1) {
						fileName=new String(buff);
						System.out.println(new String(buff));
					}
//					System.out.println("server ok1w");
//					BufferedReader socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//					String s = socketIn.readLine();
//					String fileName = in.readAllBytes().toString();
//					System.out.println("server ok1"+fileName);
//					String fileName = in.readAllBytes().toString();
//					char[] readstr = new char[512];
//					socketIn.readLine();
//					socketIn.read(readstr);
//					System.out.println("server ok1"+socketIn.readLine());
                    DataInputStream fis = null;
                	DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
                    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
					dis = new DataInputStream(socket.getInputStream());
//					String fileName = dis.readUTF();

                    Vector<Integer> vector = getRandom(fileList.size());
                    for(Integer integer : vector){
        	            String filePath = fileList.get(integer.intValue());
        	            file = new File(filePath);
//        	            if(fileName.equals(file.getName()))
//        	            {
        	                 fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
        	                 dos.writeUTF(fileName);
     	                     dos.flush();
     	                     dos.writeLong(file.length());
     	                     dos.flush();

     	                     int read = 0;
     	                     int passedlen = 0;
     	                     long length = file.length();    //获得要发送文件的长度
     	                     while ((read = fis.read(buf)) != -1) {
     	                    	 passedlen += read;
     	                    	 System.out.println("已经完成文件 [" + file.getName() + "]百分比: " + passedlen * 100L/ length + "%");
     	                    	 dos.write(buf, 0, read);
     	                     }

     	                     dos.flush();
     	                     fis.close();
     	                     dos.close();
     	                     socket.close();
     	                     System.out.println("文件 " + filePath + "传输完成!");
//        	            }
        	        }


                } catch (Exception e) {
                    e.printStackTrace();
                }

	        }
	    }

//	    private static Runnable sendFile(final String filePath){
//	        return new Runnable(){
//
//	            private Socket socket = null;
//	            private String ip ="localhost";
//	            private int port = 10000;
//
//	            public void run() {
//	                System.out.println("开始发送文件:" + filePath);
//	                File file = new File(filePath);
//	                if(createConnection()){
//
//	                }
//	            }
//
//	            private boolean createConnection() {
//	                try {
//	                    socket = new Socket(ip, port);
//	                    System.out.println("连接服务器成功！");
//	                    return true;
//	                } catch (Exception e) {
//	                    System.out.println("连接服务器失败！");
//	                    return false;
//	                }
//	            }
//
//	        };
//	    }


	    public static void main(String[] args) throws Exception{
	          new TransferServer().service();
	    }
}
